﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using Jb.Web.ViewModels.UtilityModels;

namespace Jb.Web.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class ContentController : BaseController
    {
		private JbEntities _Context = new JbEntities();
        
		#region Constructors
		public ContentController()
		{
		}

		public ContentController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods

        /// <summary>
        /// Default controller, shows the list of contents
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View("List", BuildContentListConfig());
        }

        /// <summary>
        /// Shows the list of contents
        /// </summary>
        /// <returns></returns>
		public ActionResult List()
        {
            return View(BuildContentListConfig());
        }

		/// <summary>
        /// Gets a Content from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0, String IsSaved = null)
        {
            Content entity = id == 0 ? new Content() : _Context.Contents.FirstOrDefault(P => P.ID == id);            
            ContentViewModel viewModel = Mapper.Map<Content, ContentViewModel>(entity);             
            if (String.Compare(IsSaved, "true", true) == 0)
                ViewData[AppConstants.ViewDataKeys.SAVED] = true;
			return View(viewModel);
        }

		/// <summary>
        /// Saves Content Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult Edit(ContentViewModel viewModel)
        {
            if (!ModelState.IsValid)
                return View(viewModel);
            if (_Context.IsDuplicateContent(viewModel.Title.ToSeoUrl(), viewModel.ID))
            {
                ModelState.AddModelError("Title", "Sorry! this Title already exists. Choose another.");
                return View(viewModel);
            }

            Content entity = null;
            if (viewModel.ID == 0)
            {
                entity = new Content();
                _Context.AddToContents(entity);
            }
            else
            {
                entity = _Context.Contents.FirstOrDefault(P => P.ID == viewModel.ID);
                //viewModel.Created = entity.Created.ToString();
            }
            entity = Mapper.Map<ContentViewModel, Content>(viewModel, entity);

            entity.ModifiedBy = LoggedInUser.ID;
            if (viewModel.ID == 0)
            {
                entity.CreatedOn = DateTime.Now;
            }
            entity.ModifiedOn = DateTime.Now;
            entity.Url = viewModel.Title.ToSeoUrl();

            _Context.SaveChanges();

            ///Rebuild the Content and Company Route Cache, and re-map them in the global routing cache            
            MvcApplication.RefreshRoutes(true);
            //return RedirectToAction("Index");
			return RedirectToAction(String.Format("Edit/{0}", entity.ID), new { IsSaved = "true" });
        }		
		#endregion Action Methods
		
		#region Helper Methods

		/// <summary>
        /// Builds a ListConfig object with a list of Content
        /// </summary>
        /// <returns></returns>
		private ListConfig BuildContentListConfig()
		{
			UtilityDAO dao = new UtilityDAO();
            //Jb.Domain.DbParameter[] parameters = new[]{
                //new Jb.Domain.DbParameter("@JobSeekerID", LoggedInUser.JobSeekerID)
            //};
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_CONTENT_LIST, null, true);
            ListConfig listConfig = new ListConfig(ds.Tables[0], null);
            return listConfig;
		}

        #endregion			
    }
}


